package com.ruoyi.oar.controller.pc;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.oar.domain.dto.OarVerifiTaskDTO;
import com.ruoyi.oar.domain.query.OarVerifiTaskQuery;
import com.ruoyi.oar.service.OarVerifiTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * 核查任务Controller
 * 
 * @author oar
 * @date 2022-02-26
 */
@Api(tags = "PC核查任务")
@RestController
@RequestMapping("/pc/oar-verifi-tasks")
public class PcVerifiTaskController extends BaseController
{
    @Autowired
    private OarVerifiTaskService oarVerifiTaskService;

    /**
     * 查询核查任务列表
     */
    @ApiOperation("查询核查任务列表")
    //@PreAuthorize("@ss.hasRole('')")
    @GetMapping
    public TableDataInfo<OarVerifiTaskDTO> list(OarVerifiTaskQuery oarVerifiTaskQuery){
        logger.debug("查询核查任务列表,查询条件oarVerifiTaskQuery={}",JSONObject.toJSONString(oarVerifiTaskQuery));
        startPage();
        //oarVerifiTaskQuery.setVerifiDeptId(getDeptId());
        return oarVerifiTaskService.findAll(oarVerifiTaskQuery);
    }

    /**
     * 导出核查任务列表
     */
    @ApiOperation("导出核查任务列表")
    //@PreAuthorize("@ss.hasRole('')")
    @Log(title = "核查任务", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(OarVerifiTaskQuery oarVerifiTaskQuery){
        logger.debug("查询核查任务列表,导出条件oarVerifiTaskQuery={}",JSONObject.toJSONString(oarVerifiTaskQuery));
        List<OarVerifiTaskDTO> list = oarVerifiTaskService.selectOarVerifiTaskList(oarVerifiTaskQuery);
        ExcelUtil<OarVerifiTaskDTO> util = new ExcelUtil<OarVerifiTaskDTO>(OarVerifiTaskDTO.class);
        return util.exportExcel(list, "核查任务数据");
    }

    /**
     * 获取核查任务详细信息
     */
    @ApiOperation("获取核查任务详细信息")
    //@PreAuthorize("@ss.hasRole('')")
    @GetMapping(value = "/{id}")
    public Response<OarVerifiTaskDTO> getInfo(@PathVariable("id") @ApiParam("核查任务ID") String id) {
        logger.debug("获取核查任务详细信息,id={}",id);
        checkId(id);
        return Response.success(oarVerifiTaskService.selectOarVerifiTaskById(id).orElseThrow(()->new ServiceException("无效的ID")));
    }

    /**
     * 临时网约房下发核查任务
     */
    @ApiOperation("临时网约房下发核查任务")
    //@PreAuthorize("@ss.hasRole('')")
    @Log(title = "临时网约房下发核查任务", businessType = BusinessType.INSERT)
    @PostMapping
    @RepeatSubmit
    public AjaxResult add(@RequestBody OarVerifiTaskDTO oarVerifiTaskDTO) {
        logger.debug("新增核查任务,oarVerifiTaskDTO={}",JSONObject.toJSONString(oarVerifiTaskDTO));
        return toAjax(oarVerifiTaskService.insertOarVerifiTask(oarVerifiTaskDTO));
    }

    /**
     * 修改核查任务
     */
    @ApiOperation("修改核查任务")
    //@PreAuthorize("@ss.hasRole('')")
    @Log(title = "核查任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OarVerifiTaskDTO oarVerifiTaskDTO) {
        logger.debug("修改核查任务,oarVerifiTaskDTO={}",JSONObject.toJSONString(oarVerifiTaskDTO));
        checkId(oarVerifiTaskDTO.getId());
        return toAjax(oarVerifiTaskService.updateOarVerifiTask(oarVerifiTaskDTO));
    }

    /**
     * 删除核查任务
     */
    @ApiOperation("删除核查任务")
    //@PreAuthorize("@ss.hasRole('')")
    @Log(title = "核查任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        logger.debug("删除核查任务,ids={}",JSONObject.toJSONString(ids));
        Arrays.asList(ids).forEach(this::checkId);
        return toAjax(oarVerifiTaskService.deleteOarVerifiTaskByIds(ids));
    }

    @ApiOperation("更新任务状态")
    //@PreAuthorize("@ss.hasRole('')")
    @Log(title = "核查任务", businessType = BusinessType.UPDATE)
    @PutMapping("/upTaskState")
    public AjaxResult upTaskState(@RequestParam(required = false) @ApiParam("任务id") String id,@RequestParam(required = false) @ApiParam("任务状态") Integer taskState) {
        checkId(id);
        if (ToolUtil.isEmpty(taskState)) {
            throw new ServiceException("taskState不能为空");
        }
        oarVerifiTaskService.selectOarVerifiTaskById(id).map(oarVerifiTaskDTO -> {
            if(0!=oarVerifiTaskDTO.getTaskState()){
                throw new ServiceException("流程错误");
            }
            return true;
        }).orElseThrow(()->new ServiceException("任务不存在"));
        OarVerifiTaskDTO oarVerifiTaskDTO = new OarVerifiTaskDTO();
        oarVerifiTaskDTO.setId(id);
        oarVerifiTaskDTO.setTaskState(taskState);
        return toAjax(oarVerifiTaskService.updateOarVerifiTask(oarVerifiTaskDTO));
    }


    @ApiOperation("提交任务")
    //@PreAuthorize("@ss.hasRole('')")
    @Log(title = "提交任务", businessType = BusinessType.UPDATE)
    @PutMapping("/commitTask")
    public AjaxResult commitTask(@RequestParam(required = false) @ApiParam("任务id") String id) {
        checkId(id);
        oarVerifiTaskService.selectOarVerifiTaskById(id).map(oarVerifiTaskDTO -> {
            if(1!=oarVerifiTaskDTO.getTaskState()){
                throw new ServiceException("流程错误");
            }
            return true;
        }).orElseThrow(()->new ServiceException("任务不存在"));


        OarVerifiTaskDTO oarVerifiTaskDTO = new OarVerifiTaskDTO();
        oarVerifiTaskDTO.setId(id);
        oarVerifiTaskDTO.setTaskState(2);
        //oarVerifiTaskDTO.setVerifiDeptId(getDeptId());
        return toAjax(oarVerifiTaskService.commitTask(oarVerifiTaskDTO));
    }


    @ApiOperation("统计该批次必填是否已全填")
    @GetMapping(value = "countByTaskId")
    public AjaxResult countByTaskId(@RequestParam(required = false) @ApiParam("任务id") String taskId){
        if (ToolUtil.isEmpty(taskId)) {
            throw new ServiceException("taskId不能为空");
        }
        return AjaxResult.success(oarVerifiTaskService.countByTaskId(taskId));
    }

    @ApiOperation("统计核查任务数量")
    @GetMapping(value = "countByTaskState")
    public AjaxResult countByTaskState(@RequestParam(required = false) @ApiParam("任务状态 0待受理 1核查结果录入 ") Integer taskState){
        if (ToolUtil.isEmpty(taskState)) {
            throw new ServiceException("taskState不能为空");
        }
        return AjaxResult.success(oarVerifiTaskService.countByTaskState(taskState));
    }

    /**
     * 校验
     * @param id
     */
    private void checkId(String id) {
        Optional.of(id).orElseThrow(() -> new ServiceException("ID不能为空"));
        oarVerifiTaskService.selectOarVerifiTaskById(id).orElseThrow(() -> new ServiceException("无效的ID"));
    }
}
